package com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.Menu;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.R;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * zhangyue
 */
public class UIUtil {

    static public void hideSoftKeyboard(Activity activity) {
        viewHideKeyboard(activity, activity.getWindow().getDecorView().getWindowToken());
    }

    public static void viewShowKeyboard(View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }

    public static void viewHideKeyboard(Context context, IBinder windowToken) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(windowToken, 0);
    }

    /**
     * 需要在调用show之后，实际show之前调用
     */
    public static void dialogShowKeyboard(Dialog dialog) {
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

/*    public static int getThemeColor(Context context, int id) {
        *//*获取主题颜色*//*
        *//*TypedArray a = context.getTheme().obtainStyledAttributes(R.style.APPTheme, new int[]{id});
        return a.getColor(0, context.getResources().getColor(R.color.accent_material_light));*//*

        return context.getResources().getColor(R.color.theme_color_primary);
    }*/

    /**
    * 获取状态条高度
    * */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object o = null;
        Field f = null;
        int x = 0, statusHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            o = c.newInstance();
            f = c.getField("status_bar_height");
            x = Integer.parseInt(f.get(o).toString());
            statusHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }


    /**
     * 设置状态栏颜色，layout中一定要加android:fitsSystemWindows="true"
     */
    public static void setStatusBarColor(Activity activity, @ColorInt int color) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(activity, true);
        }
        // create our manager instance after the content view is set
        SystemBarTintManager tintManager = new SystemBarTintManager(activity);
        // enable status bar tint
        tintManager.setStatusBarTintEnabled(true);
        // set a custom tint color for all system bars
        tintManager.setStatusBarTintColor(color);
    }

    public static void setStatusBarColorRes(Activity activity, @ColorRes int res) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(activity, true);
        }
        // create our manager instance after the content view is set
        SystemBarTintManager tintManager = new SystemBarTintManager(activity);
        // enable status bar tint
        tintManager.setStatusBarTintEnabled(true);
        // set a custom tint color for all system bars
        tintManager.setStatusBarTintResource(res);
    }

    @TargetApi(19)
    private static void setTranslucentStatus(Activity activity, boolean on) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public static int colorHighLighted(int color) {
        int r = (color >> 16) & 0xFF;
        int g = (color >> 8) & 0xFF;
        int b = color & 0xFF;

        return Color.argb(150, r, g, b);
    }
    public static void setNumberPickerDividerColor(NumberPicker numberPicker, int color) {
        Field[] pickerFields = NumberPicker.class.getDeclaredFields();
        for (Field pf : pickerFields) {
            if (pf.getName().equals("mSelectionDivider")) {
                pf.setAccessible(true);
                try {
                    //设置分割线的颜色值
                    pf.set(numberPicker, new ColorDrawable(color));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

  /*  public static void setDatePickerDividerColor(DatePicker datePicker, int color) {
        ArrayList<NumberPicker> list = CommonUtils.findViewByType(datePicker, NumberPicker.class);

        for (NumberPicker numberPicker : list) {
            setNumberPickerDividerColor(numberPicker, color);
        }
    }*/

   /* public static void setTimePickerDividerColor(TimePicker timePicker, int color) {
        ArrayList<NumberPicker> list = CommonUtils.findViewByType(timePicker, NumberPicker.class);

        for (NumberPicker numberPicker : list) {
            setNumberPickerDividerColor(numberPicker, color);
        }
    }*/

    /**
     * 使用drawableCompat着色后press状态无法生效，
     * 但是把button添加包含press状态的背景后，着色就可以生效。
     * 所以使用这个方法着色的图片都要把背景设置为一个selector，里面包含需要着色的状态
     */
    public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable).mutate();
        DrawableCompat.setTintList(wrappedDrawable, colors);
        return wrappedDrawable;
    }

    /*public static void tintImage(ImageView imageView) {

        ColorStateList colorStateList = ContextCompat.getColorStateList(imageView.getContext(), R.color.app_button_image_tint);

        Drawable oldDrawable = imageView.getDrawable();
        Drawable tintedDrawable = tintDrawable(oldDrawable, colorStateList);
        imageView.setImageDrawable(tintedDrawable);
    }*/

   /* public static void tintImage(TextView textView) {

        ColorStateList colorStateList = ContextCompat.getColorStateList(textView.getContext(), R.color.app_button_image_tint);

        Drawable compoundDrawables[] = textView.getCompoundDrawablesRelative();
        for (int i = 0; i < compoundDrawables.length; i++) {
            Drawable oldDrawable = compoundDrawables[i];
            if (oldDrawable != null) {
                Drawable tintedDrawable = tintDrawable(oldDrawable, colorStateList);
                *//*这一步必须，否则会错位,或者用setCompoundDrawablesRelativeWithIntrinsicBounds*//*
                //tintedDrawable.setBounds(0, 0, tintedDrawable.getIntrinsicWidth(), tintedDrawable.getIntrinsicHeight());
                compoundDrawables[i] = tintedDrawable;
            }
        }
        textView.setCompoundDrawablesRelativeWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2], compoundDrawables[3]);
    }*/

   /* public static void setButtonLevel(Button button, int level) {

        Drawable compoundDrawables[] = button.getCompoundDrawablesRelative();
        for (Drawable oldDrawable : compoundDrawables) {
            if (oldDrawable != null) {
                oldDrawable.setLevel(level);
            }
        }

        button.setCompoundDrawablesRelativeWithIntrinsicBounds(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2], compoundDrawables[3]);
    }*/

    public static void setMenuIconAlwaysShow(Menu menu) {
    /*溢出菜单中始终显示icon*/
        if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
            try {
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                method.setAccessible(true);
                method.invoke(menu, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*物理按键手机上也显示三个点的菜单*/
    public static void setShowOverflowMenuAlways(Context context) {
        try {
            ViewConfiguration config = ViewConfiguration.get(context);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
